<?php
// 启动Composer自动加载
require_once 'vendor/autoload.php';

use App\Router;
use App\Controllers\UserController;
use App\Controllers\ScoreController;

// ==================== 添加 CORS 支持 ====================
header("Access-Control-Allow-Origin: http://127.0.0.1:5500"); // 允许前端来源
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS"); // 允许的方法
header("Access-Control-Allow-Headers: Content-Type, Authorization"); // 允许的请求头
header("Access-Control-Max-Age: 3600"); // 预检缓存时间（秒）

// 处理预检请求（OPTIONS）
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}
// =========================================================

// 创建路由实例
$router = new \App\Router();

// 创建控制器实例
$userController = new UserController();
$scoreController = new ScoreController();

// 定义路由
// 用户的路由
$router->add('GET', '/api/users/search', [$userController, 'search']);
$router->add('GET', '/api/users', [$userController, 'index']);
$router->add('GET', '/api/users/{id}', [$userController, 'show']);
$router->add('POST', '/api/users', [$userController, 'create']);
$router->add('PUT', '/api/users/{id}', [$userController, 'update']); // 补全 PUT 路由
$router->add('DELETE', '/api/users/{id}', [$userController, 'delete']); // 补全 DELETE 路由

// 成绩的路由
$scoreController = new \App\Controllers\ScoreController();
$router->add('GET', '/api/scores', [$scoreController, 'getCourseScoreAction']);
$router->add('GET', '/api/scores/search', [$scoreController, 'searchByCourseOrMajorAction']);
$router->add('DELETE', '/api/scores', [$scoreController, 'deleteScoreAction']);
$router->add('PUT', '/api/scores', [$scoreController, 'updateScoreAction']);


// 运行路由
$router->run();
exit;
?>